package model;

import lombok.extern.slf4j.Slf4j;
import utils.TunnelLoggerFactory;
import wei.yigulu.iec104.nettyconfig.Iec104MasterBuilder;
import wei.yigulu.iec104.util.SendDataFrameHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 104通道
 */
@Slf4j
public class Iec104Master {

	SysIpconfig sysIpconfig;

	Iec104MasterBuilder iec104MasterBuilder;

	Map<Integer, ModusTable> modusTableMap = new HashMap<>();

	Integer callLag;

	public Iec104Master(SysIpconfig sysIpconfig, List<ModusTable> modusTables) {
		this.sysIpconfig = sysIpconfig;
		for (ModusTable m : modusTables) {
			this.modusTableMap.put(m.modus, m);
		}
		this.callLag = sysIpconfig.callLag;
		iec104MasterBuilder = new Iec104MasterBuilder(sysIpconfig.getIp(), Integer.parseInt(sysIpconfig.getPort()));
		iec104MasterBuilder.setLog(TunnelLoggerFactory.getLogger(this.sysIpconfig.getId()));
		iec104MasterBuilder.getConfigInfoMap().put("ModusTable", this.modusTableMap);
	}


	public void start() {
		if (this.iec104MasterBuilder != null) {
			this.iec104MasterBuilder.createByUnBlock();
		}
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
			if (this.iec104MasterBuilder.isConnected()) {
				try {
					SendDataFrameHelper.sendTotalSummonFrame(iec104MasterBuilder.getFuture().channel(), 1, 6, iec104MasterBuilder.getLog());
				} catch (Exception e) {
					log.error("通道:{}发送总召唤失败", sysIpconfig.getId(), e);
				}
			} else {
				log.warn("通道:{}当前未连接成功", sysIpconfig.getId());
			}
		}, callLag, callLag, TimeUnit.SECONDS);
	}

}
